﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.ServiceModel;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using RemoteControlService;
using Autofac;
using RemoteImaging.ConfigurationSectionHandlers;
using RemoteImaging.LicensePlate;


namespace RemoteImaging
{
    using RealtimeDisplay;
    using System.Xml;

    static class Program
    {
        public static string directory;
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] argv)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += Application_ThreadException;




            bool createdNew;
            var mutex = new Mutex(true, "A8AD9F58-C6FB-49EE-A33E-35B3E608F6FE", out createdNew);
            if (!createdNew)
            {
                MessageBox.Show("程序正在运行或者正在退出，请稍候重试。",
                    Properties.Settings.Default.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }


            if (!Directory.Exists(Properties.Settings.Default.OutputPath))
            {
                using (var dlg = new FormChooseDirectory())
                {
                    dlg.ShowDialog();
                }
            }

            DevExpress.Utils.AppearanceObject.DefaultFont = new Font("Tahoma",
                                                                     Properties.Settings.Default.DefaultFontSize);

            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();

            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(Properties.Settings.Default.SkinUsed);

            IDataStore dataStore = null;

            int count = 0;
        RETRY:
            try
            {
                dataStore = XpoDefault.GetConnectionProvider(//AccessConnectionProvider.GetConnectionString("LicensePlate.mdb"),
    MSSqlConnectionProvider.GetConnectionString(Properties.Settings.Default.SqlInstanceName, "MobilePolice"),
    AutoCreateOption.DatabaseAndSchema);
            }
            catch (Exception ex)
            {
                ++count;
                if (count == 3)
                {
                    MessageBox.Show("无法连接数据库，错误信息如下:\r\n\r\n" + ex.Message, "数据库", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    //让sqlserver有时间启动。
                    System.Threading.Thread.Sleep(3000);
                    goto RETRY;
                }
            }


            using (SimpleDataLayer dataLayer = new SimpleDataLayer(dataStore))
            {
                using (Session session = new Session(dataLayer))
                {
                    session.UpdateSchema();
                    session.CreateObjectTypeRecords(
                        typeof(Damany.PortraitCapturer.DAL.DTO.CapturedImageObject),
                        typeof(Damany.PortraitCapturer.DAL.DTO.Video),
                        typeof(Damany.PortraitCapturer.DAL.DTO.Portrait),
                        typeof(Damany.PortraitCapturer.DAL.DTO.Frame));
                    var cachNode = new DataCacheNode(new DataCacheRoot(dataStore));
                    XpoDefault.DataLayer = new ThreadSafeDataLayer(session.Dictionary, cachNode);
                }
            }


            LicensePlateInfo.ImageStoreRootPath = System.IO.Path.Combine(Properties.Settings.Default.OutputPath, "LicensePlateImage");


            //for (int i = 0; i < 100; i++)
            //{
            //    using (var session = new Session())
            //    {
            //        session.BeginTransaction();
            //        for (int j = 0; j < 1000; j++)
            //        {
            //            var rci = new ReportedCarInfo(session)
            //                          {
            //                              CarFrameNumber = j.ToString("d8"),
            //                              CarType = j.ToString(),
            //                              CaseNumber = j.ToString("d8"),
            //                              CreationTime = DateTime.Now,
            //                              EngineNumber = j.ToString("d10"),
            //                              LicenseNumber = j.ToString("d6"),
            //                              Url = j.ToString("d20")
            //                          };
            //            rci.Save();

            //            //System.Diagnostics.Debug.WriteLine(i);
            //        }
            //        session.CommitTransaction();
            //    }
            //}


            //return;)

            try
            {
                var modeCollection = new DevExpress.Xpo.XPCollection<WorkModeCamSetting>(new Session());
                modeCollection.Load();

                if (modeCollection.Count == 0)
                {
                    var session = new Session();
                    var workingModeSettings = new WorkModeCamSetting(session);

                    workingModeSettings.ModeName = "室外模式";
                    workingModeSettings.ShutterSpeed = 4;
                    workingModeSettings.IrisLevel = 40;
                    workingModeSettings.Save();

                    workingModeSettings = new WorkModeCamSetting(session);
                    workingModeSettings.ShutterSpeed = 1;
                    workingModeSettings.IrisLevel = 50;
                    workingModeSettings.ModeName = "室内模式";
                    workingModeSettings.Save();

                    session.Dispose();
                }

                foreach (var workModeCamSetting in modeCollection)
                {
                    var dummy = workModeCamSetting;
                    System.Diagnostics.Debug.WriteLine(dummy);
                }





                var strapper = new StartUp();
                strapper.Start();


                var mainForm = strapper.Container.Resolve<RemoteImaging.RealtimeDisplay.MainForm>();
                var controller = strapper.Container.Resolve<MainController>();
                mainForm.AttachController(controller);


                mainForm.ButtonsVisible =
                    (ButtonsVisibleSectionHandler)System.Configuration.ConfigurationManager.GetSection("FaceDetector.ButtonsVisible");

                try
                {
                    StartLicensePlateMonitor(strapper.Container);
                    WireupNavigation(strapper.Container);

                    RegisterLicensePlateRepository(strapper);
                }
                catch (Exception e)
                {
                    HandleException(e);
                }


                Application.Run(mainForm);

            }
            catch (Exception e)
            {
                HandleException(e);
            }

            GC.KeepAlive(mutex);
        }

        private static void RegisterLicensePlateRepository(StartUp strapper)
        {
            //var repository = strapper.Container.Resolve<LicensePlateRepository>();
            var suspectLicensePlateCheck = strapper.Container.Resolve<SuspectLicensePlateChecker>();
            strapper.Container.Resolve<SuspectCarChecker>();
        }


        private static void WireupNavigation(Autofac.IContainer container)
        {
            var navController = container.Resolve<YunTai.NavigationController>();
            navController.Start();
        }

        private static void StartLicensePlateMonitor(Autofac.IContainer container)
        {

            var monitor = container.Resolve<LicensePlate.LicensePlateUploadMonitor>();
            monitor.Start();

            System.GC.KeepAlive(monitor);

        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private static void HandleException(Exception e)
        {
            LogException(e);
            ShowException(e);
        }

        private static void ShowException(System.Exception e)
        {
            MessageBox.Show(e.Message, "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private static void LogException(System.Exception e)
        {
            _logger.FatalException(e.Message, e);
        }


        static void watcher_ImagesUploaded(object Sender, ImageUploadEventArgs args)
        {
            DateTime time = args.Images[0].CaptureTime;
            string msg = string.Format("camID={0} count={1} time={2}", args.CameraID, args.Images.Length, time);
            System.Diagnostics.Debug.WriteLine(msg);
        }
    }
}
